/**
 * 用户相关服务
 */
var util = require('../utils/util.js');
var api = require('../config/api.js');

/**
 * 调用微信登录
 */
function loginByWeixin(userProfile) {
  let code = null;
  return new Promise(function (resolve, reject) {
    return util.login().then((res) => {
      code = res.code;
      return userProfile;
    }).then((userProfile) => {
      //登录远程服务器
      util.request(api.AuthLoginByWeixin, { code: code, encrypted_data: userProfile.encryptedData, iv: userProfile.iv }).then(res => {
        if (res.code === 0) {
          //存储用户信息
          // wx.setStorageSync('userInfo', res.data.userInfo);
          wx.setStorageSync('token', res.data.access_token);
          if(res.phone_number){
            wx.setStorageSync('phone',res.data.phone_number);
          }else{
            wx.setStorageSync('phone','0');
          }
          wx.setStorageSync('session_key',res.data.session_key);
          wx.setStorageSync('is_auth',res.data.is_auth);
          resolve(res);
        } else {
          util.showErrorToast(res.message)
          reject(res);
        }
      }).catch((err) => {
        reject(err);
      });
    }).catch((err) => {
      console.log(err)
      reject(err);
    })
  });
}

/**
 * 判断用户是否登录
 */
function checkLogin() {
  return new Promise(function (resolve, reject) {
    if (wx.getStorageSync('token')) {
      util.checkSession().then(() => {
        resolve(true);
      }).catch(() => {
        reject(false);
      });
    } else {
      reject(false);
    }
  });
}


/**
 * Promise封装wx.login
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

module.exports = {
  loginByWeixin,
  checkLogin,
};











